<?php

namespace app\admin\controller\check;

use app\admin\model\Lift;
use app\admin\model\OrderServiceSales;
use app\admin\model\SalesOrder;
use app\admin\model\User;
use app\common\controller\Backend;
use app\common\library\Auth;
use app\model\crud\Cleaner;
use app\model\crud\StoreOrderService;
use think\Db;
use think\Exception;

/**
 * 课程管理
 *
 * @icon fa fa-user
 */
class service extends Backend
{

    protected $relationSearch = true;
    protected $searchFields = 'id,username,nickname';
    protected $noNeedRight = ['select_school_class', 'select_teacher', 'select_class_room', 'getClassRoom', 'getTeacher', 'getSchoolClass'];

    /**
     * @var \app\admin\model\User
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = model('Service');
    }

    /**
     * 查看
     */
    public function index()
    {
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            $where = [];
            $filter = $this->request->get('filter');
            $offset = $this->request->get('offset');
            $order = $this->request->get('order');
            $sort = $this->request->get('sort');
            $limit = $this->request->get('limit');
            $filter = json_decode($filter, true);
            $string = '';
            foreach ($filter as $w => $v) {
                if ($w == 'service_time' || $w == 'cleaning_end_time') {
                    $time_arr = explode(' - ', $v);
                    $where[$w] = ['between', [strtotime($time_arr[0]), strtotime($time_arr[1])]];
                    //  $where_new['end_time'] = ['<=',$time_arr[1]];
                } else if ($w == 'add_time') {
                    $time_arr = explode(' - ', $v);
                    $where['service.add_time'] = ['between', [strtotime($time_arr[0]), strtotime($time_arr[1])]];
                    //  $where_new['end_time'] = ['<=',$time_arr[1]];
                } else if ($w == 'freeze' || $w == 'package' || $w == 'duration' || $w == 'cleaning_id') {
                    $where[$w] = $v;
                } else if ($w == 'province' || $w == 'city' || $w == 'area') {
                    $string .= $v . '-';
                } else if ($w == 'status') {
                    if ($v == '-1') {
                        $where['service.status'] = ['in', [-1, -2]];
                    } else {
                        $where['service.status'] = $v;
                    }
                } else if ($w == 'lifts.lift_number') {
                    $where['lift.lift_number | free.elevator_no'] = ['like', '%' . $v . '%'];
                } else if ($w == 'lifts.real_name') {
                    $where['lift.real_name | free.proprietor_name'] = ['like', '%' . $v . '%'];
                } else if ($w == 'lifts.phone') {
                    $where['lift.phone | free.phone'] = ['like', '%' . $v . '%'];
                } else if ($w == 'lifts.specific_address') {
                    $where['lift.specific_address | free.specific_address'] = ['like', '%' . $v . '%'];
                } else if ($w == 'lifts.specifications_name') {
                    $where['specifications'] = $v;
                }
            }
            if ($string) {
                $string = substr($string, 0, -1);
                $where['lift.area | free.address'] = $string;
            }
            $count = $this->model
                ->with(['lift', 'order', 'sales', 'free'])
                ->where($where)
                ->count();
            $list = $this->model
                ->with(['lift', 'order', 'sales', 'free'])
                ->where($where)
                ->order($sort, $order)
                ->limit($offset, $limit)
                ->select();
            foreach ($list as $w => &$v) {
                if ($v['free_clean_id'] > 0) {
                    $elevator_no = Db::name('free_clean')->where(['id' => $v['free_clean_id']])->find();
                    $v['lifts'] = [
                        'lift_number' => $elevator_no['elevator_no'],
                        'area' => $elevator_no['address'],
                        'buildings' => $elevator_no['buildings'],
                        'real_name' => $elevator_no['proprietor_name'],
                        'phone' => $elevator_no['phone'],
                        'specific_address' => $elevator_no['buildings'],
                    ];
                    //   var_dump($v['lift']);
                } else {
                    $v['lifts'] = $v['lift'];
                }
//                if (!empty($v['order'])) {
//                    $v['personnel_name'] = User::where(['uid' => $v['order']['personnel_id']])->value('real_name');
//                }
                if ($v['cleaning_id'] > 0) {
                    $v['cleaner_name'] = \app\admin\model\Cleaner::where(['uid' => $v['cleaning_id']])->value('cleaner_name');
                }
                if ($v['service_time'] > 0) {
                    $v['service_time'] = date('Y-m-d', $v['service_time']);
                }
                $v['cleaning_end_time'] = $v['cleaning_end_time'] ? date('Y-m-d', $v['cleaning_end_time']) : '';
                if (empty($v['sales'])) {
                    $array['handle_type'] = '暂无';
                    $list[$w]['sales'] = $array;
                }

            }
            $sql = $this->model->getLastSql();
            $result = array("total" => $count, "rows" => $list, 'sql' => $sql);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * 添加
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            $params['create_time'] = time();
            $params['admin_id'] = $this->auth->id;
            $image_arr = explode('aliyuncs.com', $params['logo']);
            if ($params['logo']) {
                $params['logo'] = $image_arr[1];
            }
            $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890';
            $randStr = str_shuffle($str);
            $rands = substr($randStr, 0, 6);
            $params['code'] = $rands;
            $res = $this->model->insert($params);
            if ($res) {
                $this->success();
            }
            $this->error();
        }
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    if ($params['service_time']) {
                        $params['service_time'] = strtotime($params['service_time']);
                    }
                    $params['update_time'] = time();
                    $params['admin_id'] = $this->auth->id;
//                    $image_arr = explode('aliyuncs.com', $params['logo']);
//                    if ($params['logo']) {
//                        $params['logo'] = $image_arr[1];
//                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
//        if ($row['logo']) {
//            $row['logo'] = 'https://yunwotuojiao.oss-cn-fuzhou.aliyuncs.com' . $row['logo'];
//        }


        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 删除
     */
    public function del($ids = "")
    {
        if (!$this->request->isPost()) {
            $this->error(__("Invalid parameters"));
        }
        $ids = $ids ? $ids : $this->request->post("ids");
        $row = $this->model->get($ids);
        $this->modelValidate = true;
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $this->model->where(['id' => $row['id']])->delete();
        $this->success();
    }

    /**
     * 详情
     */
    public function detail($ids = '')
    {
        $row = $this->model->get($ids, ['lift','sales']);
        $row = $row->toArray();
        // var_dump($w);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['update_time'] = time();
                    $params['admin_id'] = $this->auth->id;
                    $image_arr = explode('aliyuncs.com', $params['logo']);
                    if ($params['logo']) {
                        $params['logo'] = $image_arr[1];
                    }
                    $result = $row->allowField(true)->save($params);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($row['service_time'] > 0) {
            $row['service_time'] = date('Y-m-d H:i:s', $row['service_time']);
        }
        $row['order'] =  Db::name('store_order')->where(['order_id'=>$row['order_id']])->find();
        if ($row['order']['pay_time'] > 0) {
            $row['order']['pay_time'] = date('Y-m-d H:i:s', $row['order']['pay_time']);
        }
        $row['cleaner_name'] = '';
        if ($row['cleaning_id'] > 0) {
            $row['cleaner_name'] = \app\admin\model\Cleaner::where(['id' => $row['cleaning_id']])->value('cleaner_name');
        }
        // var_dump($row['order']);
        if (!empty($row['order']) && isset($row['order']['personnel_id'])) {
            $row['order']['personnel_name'] = User::where(['uid' => $row['order']['personnel_id']])->value('real_name');
        }
        if (empty($row['sales'])) {
            $array['handle_type'] = '暂无';
            $array['service_status'] = 0;
            $row['sales'] = $array;
        }
        if (empty($row['order']) || !isset($row['order']['personnel_id'])) {
            $json['personnel_name'] = '暂无';
            $json['order_id'] = '';
            $json['pay_price'] = '';
            $json['pay_time'] = '';
            $row['order'] = $json;
        }
        if ($row['free_clean_id'] > 0) {
            $elevator_no = Db::name('free_clean')->where(['id' => $row['free_clean_id']])->find();
            // $lift = Lift::where(['lift_number' => $elevator_no['elevator_no']])->find();
            $row['lifts'] = [
                'lift_number' => $elevator_no['elevator_no'],
                'area' => $elevator_no['address'],
                'buildings' => $elevator_no['buildings'],
                'real_name' => $elevator_no['proprietor_name'],
                'phone' => $elevator_no['phone'],
            ];
        } else {
            $row['lifts'] = $row['lift'];
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 详情
     */
    public function do_assign($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");

            if ($params) {
                if (!empty($params['id'])) {
                    $params['cleaning_id'] = $params['id'];
                    unset($params['id']);
                }
                if (!empty($params['uid'])) {
                    $params['cleaning_id'] = $params['uid'];
                    unset($params['uid']);
                    unset($params['id']);
                }
                $time = $row['service_time'] - 86400 * 2;
                if ($time > time()) {
                    $this->error('指派阿姨不能选择三天后');
                }
                if ($row['freeze'] == '1') {
                    $this->error('该订单已冻结');
                }
                try {
                    $params['up_time'] = time();
                    $data = [
                        'cleaning_id' => $params['cleaning_id'],
                    ];
                    $result = $row->allowField(true)->save($data);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        if ($row['cleaning_id'] > 0) {
            $row['cleaner_name'] = \app\admin\model\Cleaner::where(['id' => $row['cleaning_id']])->value('cleaner_name');
        } else {
            $row['cleaner_name'] = '';
        }
        $row['is_have_saleman'] = 0;
        if ($row['cleaner_name']) {
            $row['is_have_saleman'] = 1;
        }
        if (empty($row['sales'])) {
            $array['handle_type'] = '暂无';
            $array['service_status'] = 0;
            $row['sales'] = $array;
        }
        if (empty($row['order'])) {
            $json['personnel_name'] = '暂无';
            $json['order_id'] = '';
            $json['pay_price'] = '';
            $json['pay_time'] = '';
            $row['order'] = $json;
        }
        if ($row['free_clean_id'] > 0) {
            $elevator_no = Db::name('free_clean')->where(['id' => $row['free_clean_id']])->find();
            $lift = Lift::where(['lift_number' => $elevator_no['elevator_no']])->find();
            if (!empty($lift)) {
                $row['lift'] = $lift;
            } else {
                $row['lift'] = [
                    'lift_number' => $elevator_no['elevator_no'],
                    'area' => $elevator_no['address'],
                    'buildings' => $elevator_no['buildings'],
                    'real_name' => $elevator_no['proprietor_name'],
                    'phone' => $elevator_no['phone'],

                ];
            }
        }
        $this->view->assign("row", $row);
        $this->assignconfig("is_have_saleman", $row['is_have_saleman']);
        $this->assignconfig("service_id", $row['service_id']);
        return $this->view->fetch();
    }

    /**
     * 获取保洁员
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getSaleMan()
    {
        $keValue = $this->request->request("keyValue");
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            $show_province_id = [];
            $new_where = [

            ];
            if ($keValue) {
                $keValue = explode(',', $keValue);
                // $new_arr = array_merge($keValue,$show_province_id);
                $new_where = [
                    'id' => ['in', $keValue]
                ];
            }

            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $total = Db::name('cleaner')
                ->where($where)
                ->where($new_where)
                ->count();

            $list = Db::name('cleaner')
                ->where($where)
                ->where($new_where)
                ->order('uid desc')
                ->select();
            $sql = Db::name('cleaner')->getLastSql();
            $list = collection($list)->toArray();
            $new_list = [];
            foreach ($list as $w => $v) {
                if ($v['status'] == 1) {
                    $v['title1'] = '-上线';
                } else if ($v['status'] == 2) {
                    $v['title1'] = '-下线';
                } else {
                    $v['title1'] = '-离职';
                }
                $new_data = [
                    'id' => $v['uid'],
//                    'province_id' => $v['province_id'],
                    'title' => $v['cleaner_name'].$v['title1'],
                ];
                $new_list[$w] = $new_data;
            }
            $result = array("total" => $total, "list" => $new_list, "sql" => $sql);
            return json($result);
        }
    }

    /**
     * 保洁员列表--按距离
     */
    public function cleaner_list()
    {
        $service_id = $this->request->request("service_id");
        $model = Db::name('cleaner')->where('status', 1);
        $list = $model->select();
        $service = \app\admin\model\Service::with(['lift'])->where(['service_id' => $service_id])->find();
        foreach ($list as $k => $v) {
            //计算每个阿姨的lon和lat和$service['lift']数组里面lon和lat的距离
            $list[$k]['distance'] = round(distance($v['lon'], $v['lat'], $service['lift']['lon'], $service['lift']['lat']), 1);
            //计算每个阿姨今天的服务次数
            $where['cleaning_id'] = $v['uid'];
            $where['service_time'] = ['between', [strtotime(date('Y-m-d 00:00:00')), strtotime(date('Y-m-d 23:59:59'))]];
            $list[$k]['count'] = \app\admin\model\Service::where($where)->count();
        }
        $total = count($list);
        $sql = Db::name('cleaner')->getLastSql();
        // 从二维数组中提取count列作为排序依据
        $service_count = array_column($list, 'count');
        // 使用array_multisort()函数进行排序
        array_multisort($service_count, SORT_DESC, $list);
        // 从二维数组中提取count列作为排序依据
        $distance = array_column($list, 'distance');
        array_multisort($distance, SORT_ASC, $list);
        $result = array("total" => $total, "rows" => $list, "sql" => $sql);
        return json($result);
    }

    /**
     * 申请售后
     */
    public
    function service_after_sale($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                try {
                    $params['add_time'] = time();
                    $result_info = get_method('https://txwapi.tixiwe.com/api/v2/public/set_order?letter=Fwsale');
                    $result_info = json_decode($result_info, true);
                    $params['number'] = $result_info['data']['number'];
                    $params['personnel_id'] = Db::name('store_order')->where(['order_id' => $row['order_id']])->value('personnel_id');
                    $result = OrderServiceSales::create($params);
                    $this->model::where(['id' => $ids])->update(['status' => 5]);
                    if ($result !== false) {
                        $this->success();
                    } else {
                        $this->error($row->getError());
                    }
                } catch (\think\exception\PDOException $e) {
                    $this->error($e->getMessage());
                } catch (\think\Exception $e) {
                    $this->error($e->getMessage());
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        //获取详情信息
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 冻结订单
     */
    public
    function freeze($ids = '')
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        try {
            $status = $this->request->get('status');
            Db::startTrans();

            if ($status == 1) {
                $content = '冻结成功';
            } else $content = '解冻成功';
            $result = \app\admin\model\Service::where(['id' => $ids])->update(['freeze' => $status]);
            if ($result) {
                Db::commit();
                $this->success($content);
            }

        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

}
